<template>
  <div>
    <!-- 页面顶部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 内容显示面板 -->
    <el-card class="box-card">
      <div>
        <el-row :gutter="10">
          <el-col :span="6">
            <!-- 搜索 -->
            <el-input v-model="queryinfor.query" placeholder="请输入内容" class="input-with-select" clearable @clear="getuserlist">
              <el-button slot="append" icon="el-icon-search" @click="getuserlist" />
            </el-input>
          </el-col>
          <!-- 添加用户 -->
          <el-col :span="2">
            <el-button type="primary" @click="centerDialogVisible = true">添加用户</el-button>
          </el-col>
        </el-row>
        <!-- 用户列表 -->
        <el-table :data="userlist" style="width: 100%" border stripe :cell-style="columnclass" :header-cell-style="headercell">
          <el-table-column type="index" label="序号" width="50" />
          <el-table-column prop="username" label="姓名" width="180" />
          <el-table-column prop="email" label="邮箱" width="180" />
          <el-table-column prop="mobile" label="电话" />
          <el-table-column prop="role_name" label="角色" />
          <el-table-column label="状态">
            <!-- 用户状态作用域插槽 -->
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state" active-color="#108ee9" inactive-color="#ddd" @change="userstatechange(scope.row)" />
            </template>
          </el-table-column>
          <!-- 操作列 -->
          <el-table-column label="操作">
            <template slot-scope="scope">
              <!-- 修改 -->
              <el-button type="primary" icon="el-icon-edit" size="medium" @click="editdialog(scope.row.id)" />
              <!-- 删除 -->
              <el-button type="danger" icon="el-icon-delete" size="medium" @click="deletedialog(scope.row.id)" />
              <!-- 带提示信息的按钮 -->
              <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                <!-- 分配角色 -->
                <el-button type="warning" icon="el-icon-setting" size="medium" @click="setrole(scope.row)" />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination :current-page="queryinfor.pagenum" :page-sizes="[ 2, 4, 6]" :page-size="queryinfor.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 添加用户弹出框 -->
    <el-dialog title="添加用户" :visible.sync="centerDialogVisible" width="30%" center @close="addformreset">
      <el-form ref="addform" :model="addform" status-icon :rules="addformrules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addform.username" />
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="addform.password" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addform.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addform.mobile" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户弹出框 -->
    <el-dialog title="修改用户" :visible.sync="centerDialogVisible2" width="30%" center @close="editformreset">
      <el-form ref="editform" :model="editform" status-icon :rules="editformrules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editform.username" :disabled="true" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editform.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editform.mobile" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="edituser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="centerDialogVisible3" width="30%" center @close="restrolelist">
      <div>
        <p style="line-height:40px;">当前的用户：{{ userinfor.username }}</p>
        <p style="line-height:40px;">当前的角色：{{ userinfor.role_name }}</p>
        <p>分配新角色：
          <el-select v-model="selected" placeholder="请选择">
            <el-option v-for="item in rolelist" :key="item.id" :label="item.roleName" :value="item.id" />
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="saverole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    var checkemail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        // 合法的邮箱
        return callback()
      }

      callback(new Error('请输入合法的邮箱'))
    }
    var checkmobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return callback()
      }

      callback(new Error('请输入合法的手机号'))
    }
    return {
      userlist: [],
      total: 1,
      queryinfor: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      centerDialogVisible: false,
      centerDialogVisible2: false,
      centerDialogVisible3: false,
      addform: {},
      addformrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户名的长度在6~15个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      editform: {},
      editformrules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]

      },
      deleteid: '',
      // 需要分配角色的用户
      userinfor: {},
      rolelist: [],
      selected: ''
    }
  },
  created() {
    this.getuserlist()
  },
  methods: {
    // 表格样式回调函数
    headercell({ row, rowIndex }) {
      return 'text-align:center'
    },
    columnclass({ row, column, rowIndex, columnIndex }) {
      return 'text-align:center'
    },
    // 初始化函数获取用户列表信息并赋值
    async getuserlist() {
      const { data: res } = await this.$http.get('users', { params: this.queryinfor })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      } else {
        this.userlist = res.data.users
        this.total = res.data.total
      }
    },
    // 当前显示数据条数发生改变重置参数对应值并刷新用户列表
    handleSizeChange(val) {
      this.queryinfor.pagesize = val
      this.getuserlist()
    },
    // 当前显示页码发生改变重置参数对应值并刷新用户列表
    handleCurrentChange(val) {
      this.queryinfor.pagenum = val
      this.getuserlist()
    },
    // 重构用户状态信息
    async userstatechange(userinfor) {
      const { data: res } = await this.$http.put(`users/${userinfor.id}/state/${userinfor.mg_state}`)
      if (res.meta.status !== 200) {
        // 如果修改失败则将状态重置为原来的值
        userinfor.mg_state = !userinfor.mg_state
        return this.$message.error('修改失败')
      } else {
        return this.$message.success('修改成功')
      }
    },
    // 重置添加用弹窗的表单信息
    addformreset() {
      this.$refs.addform.resetFields()
    },
    // 点击确定校验表单项是否合法然后发起添加用户请求
    adduser() {
      this.$refs.addform.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addform)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        } else {
          this.centerDialogVisible = false
          // 刷新用户列表信息
          this.getuserlist()
          return this.$message.success(res.meta.msg)
        }
      })
    },
    // 修改用户列表信息
    async editdialog(info) {
      this.centerDialogVisible2 = true
      // 通过用户ID来向后台发起请求告诉后台具体修改了哪个用户的信息
      const { data: res } = await this.$http.get('users/' + info)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      } else {
        // 成功后给修改用户表单信息填充值
        this.editform = res.data
        return this.$message.success(res.meta.msg)
      }
    },
    // 重置修改用户表单信息
    editformreset() {
      this.$refs.editform.resetFields()
    },
    // 点击确定校验修改的表单信息是否合法然后将修改的表单信息重新发送给后台
    edituser() {
      this.$refs.editform.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editform.id, {
          email: this.editform.email,
          mobile: this.editform.mobile
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        } else {
          this.centerDialogVisible2 = false
          // 刷新用户列表
          this.getuserlist()
          return this.$message.success('修改成功')
        }
      })
    },
    // 弹出删除用户的对话框
    async deletedialog(id) {
      // this.centerDialogVisible3 = true
      // this.deleteid = id
      const confirmresult = await this.$confirm('此操作将永久删除用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => {
        return error
      })
      // 如果确认删除,则返回confirm
      if (confirmresult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getuserlist()
    },
    // 展示分配角色
    async setrole(row) {
      this.centerDialogVisible3 = true
      this.userinfor = row
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.rolelist = res.data
      return this.$message.success('获取成功')
      // console.log(this.rolelist)
    },
    async saverole() {
      if (!this.selected) {
        return this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userinfor.id}/role`, { rid: this.selected })
      if (res.meta.status !== 200) {
        return this.$message.error('分配失败')
      }
      this.getuserlist()
      this.centerDialogVisible3 = false
      return this.$message.success('分配成功')
    },
    restrolelist() {
      this.selected = ''
      this.userinfor = {}
    }
  }
}
</script>
<style lang="scss" scoped>
.box-card {
  margin-top: 20px;
}
.el-table {
  margin-top: 20px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
